# middlewares/token_middleware.py
from django.utils.deprecation import MiddlewareMixin
from HomeAutoAI.common.utils.ContextVar import set_cur_token, current_token


class AsyncTokenMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 从请求头中提取 Token
        token = request.headers.get('Authorization')
        if token and token.startswith('Bearer '):
            token = token[7:]  # 去掉 'Bearer ' 前缀
        set_cur_token(token)

    def process_response(self, request, response):
        # 清理当前上下文的 Token
        current_token.set(None)
        return response
